package cn.mw.cmdb.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.mw.cmdb.entity.*;
import cn.mw.cmdb.enums.InstanceDetailTabEnum;
import cn.mw.cmdb.enums.OperatorTypeDescEnum;
import cn.mw.cmdb.enums.ViewTypeEnum;
import cn.mw.cmdb.mongoMapper.ModelPropertySortMapper;
import cn.mw.cmdb.param.*;
import cn.mw.cmdb.processor.TreeOptionFactory;
import cn.mw.cmdb.processor.TreeOptionProccessor;
import cn.mw.cmdb.service.ServiceAction;
import cn.mw.cmdb.service.TableViewManageService;
import cn.mw.cmdb.service.impl.*;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.cmdb.util.CustomPageUtil;
import cn.mw.cmdb.util.DataCreateInfo;
import cn.mw.cmdb.util.InstanceInfoUtil;
import cn.mw.cmdb.view.*;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.SearchParam;
import cn.mw.components.mongodb.entity.SubCondition;
import cn.mw.components.mongodb.tool.CriteriaWrapper;
import cn.mw.log.enums.BusinessLogType;
import cn.mw.log.enums.LogLevel;
import cn.mw.microMonitorCommon.api.cmdb.TreeView;
import cn.mw.microMonitorCommon.api.common.BaseApiService;
import cn.mw.microMonitorCommon.api.common.MwOperatorLogApi;
import cn.mw.microMonitorCommon.api.common.ResponseBase;
import cn.mw.microMonitorCommon.api.user.MwUserApi;
import cn.mw.microMonitorCommon.constant.Constants;
import cn.mw.microMonitorCommon.entity.cmdb.TableHeaderItem;
import cn.mw.microMonitorCommon.entity.logmanger.InstanceChangeHisVO;
import cn.mw.microMonitorCommon.operatorlog.client.MwLogClientSimple;
import cn.mw.microMonitorCommon.param.AssetsOperatorHisSearchParam;
import cn.mw.microMonitorCommon.param.ChangeHistorySearchParam;
import cn.mw.microMonitorCommon.security.dto.MwUser;
import cn.mw.microMonitorCommon.security.utils.SecurityUtils;
import cn.mw.microMonitorCommon.util.DateUtils;
import cn.mw.microMonitorCommon.util.IDModelType;
import cn.mw.microMonitorCommon.util.ModuleIDManager;
import cn.mw.microMonitorCommon.util.SpringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.enums.ModelConfigKeyEnum.systemDevType;
import static cn.mw.cmdb.enums.PageDescEnum.*;
import static cn.mw.cmdb.service.impl.CmdbServiceManage.serviceId;
import static cn.mw.cmdb.service.impl.InstanceViewImpl.financeParentId;
import static cn.mw.cmdb.service.impl.InstanceViewImpl.mwInstanceNameKey;
import static cn.mw.cmdb.util.CMDBCommonUtil.gerAllChildIdList;
import static cn.mw.cmdb.util.CMDBTool.encryptValueHandle;
import static cn.mw.cmdb.util.CMDBTool.updateCabinetStateByMap;
import static cn.mw.cmdb.util.ListSortUtil.sortListByTypeOrder;
import static cn.mw.cmdb.util.ValConvertUtil.booleanValueConvert;
import static cn.mw.cmdb.util.ValConvertUtil.strValueConvert;
import static cn.mw.cmdb.view.InstanceInpuFieldsViewConverter.propertyListKey;
import static cn.mw.microMonitorCommon.operatorlog.client.MwLogClientCmdb.MODEL_ID_KEY;

@RequestMapping("/modelManage")
@Controller
@Tag(name = "模型管理")
@Slf4j
public class ModelController extends BaseApiService {

    private CmdbServiceManage cmdbServiceManage;

    private MessageSource messageSource;

    private ViewManager viewManager;

    private InstanceInfoUtil instanceInfoUtil;

    private TableHeaderAndDataManage tableHeaderAndDataManage;

    private String hideStatusStr = "instanceTreeSet.hideStatusFlag";
    public String instanceNameKey = "mw";
    @Autowired
    private MwLogClientSimple logClientSimple;
    @Autowired
    private TableViewManageService tableViewManageService;
    private ModuleIDManager moduleIDManager;
    @DubboReference(check = false, timeout = 10000, mock = "true")
    private MwUserApi mwUserApi;

    @DubboReference(check = false, timeout = 10000, mock = "true")
    private MwOperatorLogApi operatorLogApi;

    private ModelPropertySortMapper modelPropertySortMapper;

    public ModelController(CmdbServiceManage cmdbServiceManage
            , MessageSource messageSource, ViewManager viewManager
            , InstanceInfoUtil instanceInfoUtil, TableHeaderAndDataManage tableHeaderAndDataManage
            , ModuleIDManager moduleIDManager, ModelPropertySortMapper modelPropertySortMapper) {
        this.viewManager = viewManager;
        this.cmdbServiceManage = cmdbServiceManage;
        this.messageSource = messageSource;
        this.instanceInfoUtil = instanceInfoUtil;
        this.tableHeaderAndDataManage = tableHeaderAndDataManage;
        this.moduleIDManager = moduleIDManager;
        this.modelPropertySortMapper = modelPropertySortMapper;
    }

    @PostMapping("/addModel")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('272')")
    @Operation(summary = "新增模型")
    public ResponseBase createModel(@RequestBody @Validated ModelInfo params) throws Exception {
        String nickName = SecurityUtils.getUser().getNickName();
        cmdbServiceManage.service(params, ServiceAction.add);
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.add.getCname() + ModelMange.getDesc(),
                        OperatorTypeDescEnum.add.getCname() + params.getModelName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("add-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/updModel")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('278')")
    @Operation(summary = "更新模型")
    public ResponseBase updateModel(@RequestBody ModelInfo params) throws Exception {
        cmdbServiceManage.service(params, ServiceAction.update);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.update.getCname() + ModelMange.getDesc(),
                        OperatorTypeDescEnum.update.getCname() + params.getModelName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("upd-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/settingModelPropertyCatologList")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('283')")
    @Operation(summary = "设置模型属性分类排序")
    public ResponseBase settingModelPropertyCatologList(@RequestBody UpdateModelPropertyCatologParam param) throws Exception {
        CustomModelServiceImpl service = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        service.settingModelPropertyCatologList(param);
        return setResultSuccess(messageSource.getMessage("upd-success", null, LocaleContextHolder.getLocale()));
    }


    @PostMapping("/delModel")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('279')")
    @Operation(summary = "删除模型")
    public ResponseBase deleteModel(@RequestBody ModelInfo params) throws Exception {
        cmdbServiceManage.service(params, ServiceAction.remove);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.remove.getCname() + ModelMange.getDesc(),
                        OperatorTypeDescEnum.remove.getCname() + params.getModelName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("del-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/selModel")
    @ResponseBody
    @Operation(summary = "查看模型")
    public ResponseBase selectModel(@RequestBody ModelInfo params) throws Exception {
        Object modelInfo = cmdbServiceManage.service(params, ServiceAction.select);
        Object ret = viewManager.getViewObject(modelInfo, null);
        CMDBTool.initCreateInfoAddtional(mwUserApi, (DataCreateInfo) modelInfo, (DataCreateInfo) ret);
        return setResultSuccess(ret);
    }

    @PostMapping("/listModel")
    @ResponseBody
    @Operation(summary = "查看模型列表")
    public ResponseBase listModel(@RequestBody ModelSearchParam searchParam) throws Exception {

        SearchParam newSearchParam = null;
        if (null != searchParam.getGroupId()) {
            //重新构造查询参数
            SearchParam sub = new ModelSearchParam()
                    .in(CMDBTool.getFieldName(ModelInfo::getGroupPath), searchParam.getGroupId());

            if (StringUtils.hasText(searchParam.getOperation())) {
                newSearchParam = new ModelSearchParam().and();
                List<SearchParam> subSearchParamList = new ArrayList<>();
                subSearchParamList.add(sub);
                subSearchParamList.add(searchParam);
                newSearchParam.setSearchParamList(subSearchParamList);
                newSearchParam.setPage(searchParam.getPage());
                searchParam.setGroupId(null);
                searchParam.setPage(null);
            } else {
                newSearchParam = sub;
            }
        } else {
            newSearchParam = searchParam;
        }
        ModelSearchParam searchModelParam = new ModelSearchParam();
        BeanUtil.copyProperties(newSearchParam, searchModelParam, CopyOptions.create().setIgnoreNullValue(true));
        searchModelParam.setPage(null);
        List ret = (List) cmdbServiceManage.service(searchModelParam, ServiceAction.list);
        ViewConvertContext context = new ViewConvertContext();
        context.put(ViewConvertContext.MwuserApiKey, mwUserApi);

        //获取模型的分组信息
        ModelGroupServiceImpl service = (ModelGroupServiceImpl) cmdbServiceManage.getModelService(ModelGroupServiceImpl.ID);
        List<TreeView> list = service.getTreeList(new GroupSearchParam());
        Object groupList = viewManager.getTreeViewObject(list, null);
        List<String> ids = new ArrayList<>();
        if (groupList != null && groupList instanceof List) {
            List<TreeView> groupListInfos = (List<TreeView>) groupList;
            //获取排序后的模型分组最底层节点的groupId
            gerAllChildIdList(groupListInfos, ids);
        }
        List<ModelInfo> modelInfoList = new ArrayList<>();
        if (ret != null && ret instanceof List) {
            modelInfoList = (List<ModelInfo>) ret;
            sortListByTypeOrder(modelInfoList, CMDBTool.getFieldName(ModelInfo::getGroupId), ids, CMDBTool.getFieldName(ModelInfo::getSortNum));
        }

        Object obj = viewManager.getListViewObject(modelInfoList, ModelInfo.class, newSearchParam, context);

        return setResultSuccess(obj);
    }

    @PostMapping("/getAllNormalModelList")
    @ResponseBody
    @Operation(summary = "获取所有的普通模型")
    public ResponseBase doSelectNormalModelList() throws Exception {
        CustomModelServiceImpl service = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        ModelSearchParam searchParam = new ModelSearchParam();
        List<ModelInfo> modelInfos = service.doSelectNormalModelList(searchParam);
        return setResultSuccess(modelInfos);
    }

    @PostMapping("/addProperty")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('280')")
    @Operation(summary = "新增属性")
    public ResponseBase addProperty(@RequestBody ModelPropertyParam param) throws Exception {
        cmdbServiceManage.service(param, ServiceAction.add);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.add.getCname() + ModelProperty.getDesc(),
                        OperatorTypeDescEnum.add.getCname() + param.getName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("add-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/delProperty")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('282')")
    @Operation(summary = "删除属性")
    public ResponseBase delProperty(@RequestBody ModelPropertyParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        Map<String, String> propertyMapByModelId = service.getPropertyMapByModelId(param.getModelId());
        cmdbServiceManage.service(param, ServiceAction.remove);
        List<String> ids = param.getIds();
        String tipMessage = "";
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                if (propertyMapByModelId != null && propertyMapByModelId.containsKey(id)) {
                    String name = propertyMapByModelId.get(id);
                    tipMessage += id + ":" + name + ";";
                }
            }
        }
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.remove.getCname() + ModelProperty.getDesc(),
                        OperatorTypeDescEnum.remove.getCname() + tipMessage, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("del-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/updProperty")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('281')")
    @Operation(summary = "修改属性")
    public ResponseBase updProperty(@RequestBody ModelPropertyParam param) throws Exception {
        cmdbServiceManage.service(param, ServiceAction.update);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.update.getCname() + ModelProperty.getDesc(),
                        OperatorTypeDescEnum.update.getCname() + param.getName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess(messageSource.getMessage("upd-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/selProperty")
    @ResponseBody
    @Operation(summary = "查看属性")
    public ResponseBase selProperty(@RequestBody ModelPropertyParam param) throws Exception {
        Object ret = cmdbServiceManage.service(param, ServiceAction.select);
        return setResultSuccess(ret);
    }

    @PostMapping("/getStructPropertyId")
    @ResponseBody
    @Operation(summary = "获取结构体Id")
    public ResponseBase getStructPropertyId() throws Exception {
        String id = strValueConvert(moduleIDManager.getID(IDModelType.Model));
        return setResultSuccess(id);
    }

    @PostMapping("/listProperty")
    @ResponseBody
    @Operation(summary = "查看属性列表")
    public ResponseBase listProperty(@RequestBody PropertySearchParam param) throws Exception {
        List list = (List) cmdbServiceManage.service(param, ServiceAction.list);
        Object ret = viewManager.getListViewObject(list, ModelPropertyParam.class, param, null);
        return setResultSuccess(ret);
    }

    @PostMapping("/distinctListProperty")
    @ResponseBody
    @Operation(summary = "查看属性列表去重")
    public ResponseBase distinctListProperty(@RequestBody PropertySearchParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        List list = service.distinctListProperty(param);
        Object ret = viewManager.getListViewObject(list, ModelPropertyParam.class, param, null);
        return setResultSuccess(ret);
    }

    @PostMapping("/settingPropertyShow")
    @ResponseBody
    @Operation(summary = "修改属性视图字段显示权限")
    public ResponseBase settingPropertyShow(@RequestBody ModelPropertyParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        boolean b = service.settingPropertyShow(param);
        return setResultSuccess(b);
    }

    @PostMapping("/customPropertySort")
    @ResponseBody
    @Operation(summary = "修改属性排序Sort值")
    public ResponseBase customPropertySort(@RequestBody ModelPropertySortInfo param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        service.customPropertySort(param);
        return setResultSuccess();
    }


    @PostMapping("/getModelByListShowProperty")
    @ResponseBody
    @Operation(summary = "查看模型列表显示的属性")
    public ResponseBase getModelByListShowProperty(@RequestBody PropertySearchParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        List<PropertyInfo> modelByListShowProperty = service.getModelByListShowProperty(param.getModelId());
        return setResultSuccess(modelByListShowProperty);
    }

    @PostMapping("/getFinanceParentModels")
    @ResponseBody
    @Operation(summary = "查看所有金融元父模型")
    public ResponseBase getFinanceParentModels(@RequestBody PropertySearchParam param) throws Exception {
        // 查询模型所有父模型
        CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        ModelInfo modelInfo = modelService.selectById(param.getModelId());
        if (modelInfo == null) {
            return setResultSuccess(new ArrayList<>());
        }
        ModelSearchParam modelSearchParam = new ModelSearchParam();
        modelSearchParam.setFields(Arrays.asList(CMDBTool.getFieldName(ModelInfo::getId), CMDBTool.getFieldName(ModelInfo::getModelName)));
        modelSearchParam.setModelIds(modelInfo.getParentModelIds());
        modelSearchParam.addSubCondition(CMDBTool.getFieldName(ModelInfo::getFunctionModule), new SubCondition(CriteriaOpsType.in.name(), FunctionModuleEnum.financeReport.getCode()));
        List<ModelInfo> financeParentModelInfos = modelService.getAllModelByParentGroup(modelSearchParam);
        return setResultSuccess(financeParentModelInfos);
    }


    @PostMapping("/listAuthProperty")
    @ResponseBody
    @Operation(summary = "新增实例输入字段")
    public ResponseBase listInputProperty(@RequestBody PropertySearchParam param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        List list = service.listInputProperty(param);
        ViewConvertContext context = new ViewConvertContext();
        context.put(ModelPropertyServiceImpl.ID, service);
        String modelId = param.getModelId();
        Query query = new Query(CriteriaWrapper.where(ModelPropertySortInfo::getModelId).is(modelId));
        ModelPropertySortInfo propertySortInfo = modelPropertySortMapper.findOne(query);
        List<String> propertyIds = new ArrayList<>();
        if (propertySortInfo != null && com.alibaba.nacos.common.utils.CollectionUtils.isNotEmpty(propertySortInfo.getPropertyIds())) {
            propertyIds = propertySortInfo.getPropertyIds();
        }
        // 先按照属性顺序排列 然后按照属性分类设置的顺序排序
        List<ModelPropertyParam> modelPropertyParamList = (List<ModelPropertyParam>) list;
        Map<String, Integer> key2SortNo = new HashMap<>();
        String viewType = param.getViewType() == null ? ViewTypeEnum.instanceView.name() : param.getViewType();
        for (ModelPropertyParam modelPropertyParam : modelPropertyParamList) {
            if (!CollectionUtils.isEmpty(modelPropertyParam.getPropertyCatologList())) {
                for (PropertyCategoryVo propertyCategoryVo : modelPropertyParam.getPropertyCatologList()) {
                    if (viewType.equals(propertyCategoryVo.getViewType())) {
                        key2SortNo.put(modelPropertyParam.getId(), propertyCategoryVo.getSortNo());
                        if (!propertyIds.contains(modelPropertyParam.getId())) {
                            propertyIds.add(modelPropertyParam.getId());
                        }
                    }
                }
            }
        }
        Collections.sort(propertyIds, Comparator.comparing(o -> key2SortNo.getOrDefault(o, 1)));
        context.put(propertyListKey, propertyIds);

        viewManager.getListViewObject(list, InstanceInpuFieldsView.class, null, context);
        Object ret = context.get(InstanceInpuFieldsView.Key);

        CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        ModelInfo modelInfo = modelService.doSelectById(param.getModelId());
        List<InstanceInpuFieldsView> dataList = new ArrayList<>();
        //自定义的模型属性分类排序
        List<String> typeOrder = modelInfo.getModelPropertyCatologList();
        if (CollectionUtils.isEmpty(typeOrder)) {
            ModelPropertyCatolog propertyCatolog = new ModelPropertyCatolog();
            propertyCatolog.setModelId(param.getModelId());
            typeOrder = service.listModelPropertyCatolog(propertyCatolog);
        }
        if (ret != null && ret instanceof List) {
            dataList = (List<InstanceInpuFieldsView>) ret;
            sortListByTypeOrder(dataList, CMDBTool.getFieldName(InstanceInpuFieldsView::getType), typeOrder);
        }
        return setResultSuccess(dataList);
    }

    @PostMapping("/listCommonProperty")
    @ResponseBody
    @Operation(summary = "查询模型跟分组公共属性")
    public ResponseBase listCommonProperty(@RequestBody List<TreeViewObject> treeViewObjectList) throws Exception {
        if (CollectionUtils.isEmpty(treeViewObjectList)) {
            return null;
        }
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        List list = service.listCommonProperty(treeViewObjectList);
        Object ret = viewManager.getListViewObject(list, PropertyInfo.class, null, null);
        return setResultSuccess(ret);
    }

    @PostMapping("/addInstance")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('288')")
    @Operation(summary = "新增实例")
    public ResponseBase createInstance(@RequestBody Map params) throws Exception {
        //设置请求跳转的serverId
        params.put(serviceId, InstanceServiceImpl.ID);
        cmdbServiceManage.service(params, ServiceAction.add);
        String name = strValueConvert(params.get(mwInstanceNameKey));
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.add.getCname() + Modelinstance.getDesc(),
                        OperatorTypeDescEnum.add.getCname() + name, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess();
    }

    @PostMapping("/batchAddInstance")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('288')")
    @Operation(summary = "批量新增实例")
    public ResponseBase batchAddInstance(@RequestBody BatchAddAndUpdInstanceParam params) throws Exception {
        Object obj = cmdbServiceManage.service(params, ServiceAction.batchAdd);
        String name = "";
        if (params != null && !CollectionUtils.isEmpty(params.getParams())) {
            List<Map> mapList = params.getParams();
            List<String> collect = mapList.stream().map(s -> strValueConvert(s.get(mwInstanceNameKey))).collect(Collectors.toList());
            name = String.join(",", collect);
        }
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.batchAdd.getCname() + Modelinstance.getDesc(),
                        OperatorTypeDescEnum.batchAdd.getCname() + name, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess();
    }

    @PostMapping("/getFunctionModule")
    @ResponseBody
    @Operation(summary = "获取实例可显示的功能模块")
    public ResponseBase getFunctionModule(@RequestBody InstanceInfo param) throws Exception {
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        List<MwModelLabelValueParam> functionModule = new ArrayList<>();
        if (!Strings.isNullOrEmpty(param.getModelId())) {
            functionModule = service.getFunctionModule(param.getModelId());
        }
        return setResultSuccess(functionModule);
    }

    @PostMapping("/updInstance")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('290')")
    @Operation(summary = "更新实例")
    public ResponseBase updInstance(@RequestBody Map params) throws Exception {
        //设置请求跳转的serverId
        params.put(serviceId, InstanceServiceImpl.ID);
        cmdbServiceManage.service(params, ServiceAction.update);
        String nickName = SecurityUtils.getUser().getNickName();
        String name = strValueConvert(params.get(mwInstanceNameKey));
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.update.getCname() + Modelinstance.getDesc(),
                        OperatorTypeDescEnum.update.getCname() + name, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess();
    }

    @PostMapping("/delInstance")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('292')")
    @Operation(summary = "删除实例")
    public ResponseBase delInstance(@RequestBody InstanceIdsParam param) throws Exception {
        InstanceServiceImpl modelService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        String name = "";
        List<InstanceInfo> instanceInfoList = modelService.doListByIdsNotAuth(param.getIds());
        cmdbServiceManage.service(param, ServiceAction.batchRemove);
        List<String> collect = instanceInfoList.stream().map(s -> s.getInstanceName()).collect(Collectors.toList());
        name = String.join(",", collect);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), BusinessLogType.CMDB_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , BusinessLogType.CMDB_MANAGE.getCnName(), OperatorTypeDescEnum.remove.getCname() + Modelinstance.getDesc(),
                        OperatorTypeDescEnum.remove.getCname() + name, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));

        return setResultSuccess();
    }

    @PostMapping("/selInstance")
    @ResponseBody
    @Operation(summary = "查询实例")
    public ResponseBase selInstance(@RequestBody InstanceInfo param) throws Exception {
        InstanceInfo result = (InstanceInfo) cmdbServiceManage.service(param, ServiceAction.select);
        Map orderedMap = instanceInfoUtil.orderInstanceInfoMap(result.getData());
        encryptValueHandle(orderedMap);
        updateCabinetStateByMap(result);
        result.setData(orderedMap);
        ViewConvertContext context = new ViewConvertContext();
        context.put(ViewConvertContext.FieldViewAuthTypeKey, FieldViewAuthType.upd);
        Object ret = viewManager.getViewObject(result, context);
        return setResultSuccess(ret);
    }

    @PostMapping("/lookInstance")
    @ResponseBody
    @Operation(summary = "实例详情")
    public ResponseBase lookInstance(String viewType, @RequestBody InstanceInfo param) throws Exception {
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        Map result = service.lookInstanceInfo(param.getId(), viewType, FieldViewAuthType.sel);
        encryptValueHandle(result);
        updateCabinetStateByMap(result);
        ViewConvertContext context = new ViewConvertContext();
        context.put(ViewConvertContext.FieldViewAuthTypeKey, FieldViewAuthType.look);
        //从对应模型中获取属性类型分组数据
        PropertySearchParam propertySearchParam = new PropertySearchParam();
        propertySearchParam.setModelId(strValueConvert(result.get(MODEL_ID_KEY)));
        propertySearchParam.setInputType(FieldViewAuthType.sel.name());
        propertySearchParam.setViewType(viewType);
        propertySearchParam.setParentModelId((String) result.get(financeParentId));
        ResponseBase responseBase = listInputProperty(propertySearchParam);
        Object data = responseBase.getData();
        //将属性类型分组数据和实例查看数据转换
        context.put(InstanceInpuFieldsView.Key, data);
        Object ret = viewManager.getViewObject(result, InstanceInfoAuthViewConverter.class, context);
        return setResultSuccess(ret);
    }

    @PostMapping("/listInstance")
    @ResponseBody
    @Operation(summary = "查询实例列表")
    public ResponseBase listInstance(@RequestBody InstanceSearchParam param) throws Exception {
        List ret = (List) cmdbServiceManage.service(param, ServiceAction.list);
        ViewConvertContext context = new ViewConvertContext();
        context.put(CMDBTool.getFieldName(InstanceInfo::getModelId), param.getModelId());
        context.put(ViewConvertContext.FieldViewAuthTypeKey, FieldViewAuthType.list);
        Object obj = viewManager.getListViewObject(ret, InstanceInfo.class, param, context);
        return setResultSuccess(obj);
    }

    //当属性选择外部关联等时,下拉框等输入框返回选项信息
    @PostMapping("/intanceInputOption")
    @ResponseBody
    @Operation(summary = "查询输入关联选择")
    public ResponseBase intanceInputOption(@RequestBody PropertyTypeRef param) throws Exception {
        PropertyType propertyType = PropertyTypeManage.getPropertyType(param.getTypeId());
        Object ret = propertyType.listInputOption(param);
        return setResultSuccess(ret);
    }

    //实例信息输入时,返回允许输入的字段信息
    @PostMapping("/listAuthField")
    @ResponseBody
    @Operation(summary = "查询授权字段")
    public ResponseBase listAuthField(@RequestBody InstanceFieldParam param) throws Exception {
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        List<PropertyInfo> list = (List) service.getFields(param.getModelId(), param.getOpsType());
        instanceInfoUtil.orderInstanceInfoTableFieldList(list);
        return setResultSuccess(list);
    }

    @PostMapping("/listPropertyValueType")
    @ResponseBody
    @Operation(summary = "属性值类型列表")
    public ResponseBase listPropertyValueType() throws Exception {
        Set<PropertyType> excludes = new HashSet<>();
        //需过滤的属性集合
        excludes.add(PropertyTypeManage.getPropertyType(PropertyTypeLong.ID));
        excludes.add(PropertyTypeManage.getPropertyType(PropertyTypeInt.ID));
//        excludes.add(PropertyTypeManage.getPropertyType(PropertyTypeList.ID));
        excludes.add(PropertyTypeManage.getPropertyType(PropertyTypeUploadImg.ID));
        excludes.add(PropertyTypeManage.getPropertyType(PropertyTypeUploadFile.ID));
        List<PropertyTypeManage.PropertyTypeView> propertyTypeViews = PropertyTypeManage.listPropertyType(excludes);
        List<PropertyTypeManage.PropertyTypeView> typeList = propertyTypeViews.stream().sorted(Comparator.comparing(s -> s.getSortNum())).collect(Collectors.toList());
        return setResultSuccess(typeList);
    }

    @PostMapping("/delPropertyCatolog")
    @ResponseBody
    @Operation(summary = "删除属性分类")
    public ResponseBase delPropertyCatolog(@RequestBody ModelPropertyCatolog param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        service.delModelPropertyCatolog(param);
        return setResultSuccess(messageSource.getMessage("del-success", null, LocaleContextHolder.getLocale()));
    }

    @PostMapping("/listPropertyCatolog")
    @ResponseBody
    @Operation(summary = "属性分类列表")
    public ResponseBase listPropertyCatolog(@RequestBody ModelPropertyCatolog param) throws Exception {
        ModelPropertyServiceImpl service = (ModelPropertyServiceImpl) cmdbServiceManage.getModelService(ModelPropertyServiceImpl.ID);
        List<String> list = service.listModelPropertyCatolog(param);
//        Object obj = viewManager.getListViewObject(list, ModelPropertyCatolog.class, null ,null);
        return setResultSuccess(list);
    }

    @PostMapping("/listModelType")
    @ResponseBody
    @Operation(summary = "模型类型列表")
    public ResponseBase listModelType() throws Exception {
        List<ModelTypeView> modelTypeViews = new ArrayList<>();
        modelTypeViews.add(new ModelTypeView(ModelType.Parent.getType(), messageSource.getMessage("model-type-parent", null, LocaleContextHolder.getLocale())));
        modelTypeViews.add(new ModelTypeView(ModelType.Normal.getType(), messageSource.getMessage("model-type-normal", null, LocaleContextHolder.getLocale())));
        return setResultSuccess(modelTypeViews);
    }

    @PostMapping("/listParentModel")
    @ResponseBody
    @Operation(summary = "父模型类型列表")
    public ResponseBase listParentModel() throws Exception {
        CustomModelServiceImpl service = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        return setResultSuccess(service.findModelsForParentType());
    }

    @PostMapping("/listTableHeader")
    @ResponseBody
    @Operation(summary = "查看表头信息")
    public ResponseBase listTableHeader(@RequestBody TableSearchParam param) throws Exception {
        List<TableHeaderItem> headers = tableHeaderAndDataManage.listHeaders(param);
        return setResultSuccess(headers);
    }

    @PostMapping("/cleanTableHeader")
    @ResponseBody
    @PreAuthorize("@mwAuthorizationCheck.check('298')")
    @Operation(summary = "清空表头数据")
    public ResponseBase cleanTableHeader() throws Exception {
        tableHeaderAndDataManage.cleanTableHeader();
        return setResultSuccess();
    }

    @PostMapping("/listTableData")
    @ResponseBody
    @Operation(summary = "查看表数据信息")
    public ResponseBase listTableData(@RequestBody TableSearchParam param) throws Exception {
        return setResultSuccess(tableViewManageService.parseViewData(param));
    }

    @PostMapping("/calcInstanceCountTrend")
    @ResponseBody
    @Operation(summary = "计算汇总实例数量趋势")
    public ResponseBase calcInstanceCountTrend(@RequestBody InstanceTrendSearchParam param) throws Exception {
        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        return setResultSuccess(instanceService.calcInstanceCountTrend(param));
    }

    @PostMapping("/getVideoListCount")
    @ResponseBody
    @Operation(summary = "查看视频列表汇总信息")
    public ResponseBase getVideoListCount(@RequestBody TableSearchParam param) throws Exception {
        return setResultSuccess(tableViewManageService.getVideoListCount(param));
    }

    @PostMapping("/addCustomClassification")
    @ResponseBody
    @Operation(summary = "新增自定义分类")
    public ResponseBase addCustomClassification(@RequestBody @Validated CustomClassificationVo param) throws Exception {
        Object ret = cmdbServiceManage.service(param, ServiceAction.add);
        return setResultSuccess(ret);
    }

    @PostMapping("/deleteCustomClassification")
    @ResponseBody
    @Operation(summary = "删除自定义分类")
    public ResponseBase deleteCustomClassification(@RequestBody @Validated CustomClassificationVo param) throws Exception {
        Object ret = cmdbServiceManage.service(param, ServiceAction.remove);
        return setResultSuccess(ret);
    }

    @PostMapping("/listTableOption")
    @ResponseBody
    @Operation(summary = "查看表类型下拉选项")
    public ResponseBase listTableOption(@RequestBody TableSearchParam param) throws Exception {
        MwCMDBConfigImpl configServer = (MwCMDBConfigImpl) cmdbServiceManage.getModelService(MwCMDBConfigImpl.ID);
        MwCMDBConfigInfo cmdbConfigInfo = configServer.doSelectByKey(systemDevType.name());
        Object configValue = cmdbConfigInfo.getConfigValue();
        String systemType = "";
        if (configValue instanceof String) {
            systemType = (String) configValue;
        }
        List<ClassificationMenuVo> menuVoList = new ArrayList<>();
        TreeOptionProccessor proccessor = TreeOptionFactory.build(systemType);
        List<ClassificationMenuVo> menuVoInfoList = (List<ClassificationMenuVo>) proccessor.genTreeOption();
        if (!CollectionUtils.isEmpty(param.getShowTypeList())) {
            menuVoList = menuVoInfoList.stream().filter(s -> param.getShowTypeList().contains(s.getCode())).collect(Collectors.toList());
        } else {
            menuVoList = menuVoInfoList;
        }
        CustomClassificationServiceImpl service = (CustomClassificationServiceImpl) cmdbServiceManage.getModelService(CustomClassificationServiceImpl.ID);
        List<CustomClassificationVo> customClassificationVoList = service.selectList(new CustomClassificationVo());
        if (!CollectionUtils.isEmpty(customClassificationVoList)) {
            List<ClassificationMenuVo> finalMenuVoList = menuVoList;
            customClassificationVoList.forEach(item -> {
                finalMenuVoList.add(ClassificationMenuVo.builder().code(item.getId()).label(item.getName()).isCustom(true).build());
            });
        }
        Object ret = viewManager.getListViewObject(menuVoList, ClassificationMenuVo.class, null, null);
        return setResultSuccess(ret);
    }

    @PostMapping("/listTreeByTableOption")
    @ResponseBody
    @Operation(summary = "查看表类型树")
    public ResponseBase listTreeByTableOption(@RequestBody TableSearchParam param) throws Exception {
        String hideStatusFlag = SpringUtils.getPropertiesValue(hideStatusStr);
        if (param.getHideStatusFlag() == null) {
            param.setHideStatusFlag(booleanValueConvert(hideStatusFlag));
        }
        List list = tableHeaderAndDataManage.listTree(param);
        ViewConvertContext context = new ViewConvertContext();
        context.setSelectDropType(param.getTableId());
        context.setHideStatusFlag(param.getHideStatusFlag());
        Object ret = viewManager.getTreeViewObject(list, context);
        return setResultSuccess(ret);
    }

    @PostMapping("/queryInstanceDetail")
    @ResponseBody
    @Operation(summary = "查看资产详情tab页信息")
    public ResponseBase queryInstanceDetail(@RequestBody InstanceDetailTabParam param) throws Exception {
        InstanceDetailTabServiceImpl service = (InstanceDetailTabServiceImpl) cmdbServiceManage.getModelService(InstanceDetailTabServiceImpl.ID);
        List<MwKeyValueParam> list = new ArrayList<>();
        MwInstanceDetailTabInfo detailTabInfo = service.queryDetailTabInfo(param);
        if (detailTabInfo != null) {
            list.addAll(detailTabInfo.getTabList());
        } else {
            list.add(InstanceDetailTabEnum.getDefaultTabInfo());
        }
        return setResultSuccess(list);
    }

    @PostMapping("/detailSelectDropInfo")
    @ResponseBody
    @Operation(summary = "资产详情tab页下拉数据")
    public ResponseBase detailSelectDropInfo(@RequestBody InstanceDetailTabParam param) throws Exception {
        InstanceDetailTabServiceImpl service = (InstanceDetailTabServiceImpl) cmdbServiceManage.getModelService(InstanceDetailTabServiceImpl.ID);
        List<MwKeyValueParam> list = service.detailSelectDropInfo(param);
        return setResultSuccess(list);
    }

    @PostMapping("/saveInstanceDetail")
    @ResponseBody
    @Operation(summary = "保存资产详情tab页信息")
    public ResponseBase saveInstanceDetail(@RequestBody MwInstanceDetailTabInfo param) throws Exception {
        cmdbServiceManage.service(param, ServiceAction.add);
        return setResultSuccess(messageSource.getMessage("add-success", null, LocaleContextHolder.getLocale()));
    }


    @PostMapping("/test")
    @ResponseBody
    public ResponseBase test() {
        MwUser user = SecurityUtils.getUser();
//        List<RoleDTO> allRole = mwUserApi.getAllRole();
        return setResultSuccess(user);
    }

    @PostMapping("/saveOrUpdateTableSearchCondition")
    @ResponseBody
    @Operation(summary = "保存或更新表格搜索条件")
    public ResponseBase saveOrUpdateTableSearchCondition(@RequestBody TableSearchConditionDto param) throws Exception {
        Object ret;
        if (StringUtils.hasText(param.getId())) {
            ret = cmdbServiceManage.service(param, ServiceAction.update);
        } else {
            ret = cmdbServiceManage.service(param, ServiceAction.add);
        }
        return setResultSuccess(ret);
    }

    @PostMapping("/deleteTableSearchCondition")
    @ResponseBody
    @Operation(summary = "删除表格搜索条件")
    public ResponseBase deleteTableSearchCondition(@RequestBody TableSearchConditionDto param) throws Exception {
        return setResultSuccess(cmdbServiceManage.service(param, ServiceAction.remove));
    }

    @PostMapping("/getTableSearchConditionList")
    @ResponseBody
    @Operation(summary = "获取所有保存的查询条件列表")
    public ResponseBase getTableSearchConditionList(@RequestBody TableSearchConditionDto param) throws Exception {
        return setResultSuccess(cmdbServiceManage.service(param, ServiceAction.list));
    }

    @PostMapping("/getTableSearchConditionById")
    @ResponseBody
    @Operation(summary = "获取指定查询条件")
    public ResponseBase getTableSearchConditionById(@RequestBody TableSearchConditionDto param) throws Exception {
        return setResultSuccess(cmdbServiceManage.service(param, ServiceAction.select));
    }

    @PostMapping("/getInstanceChangeHistory")
    @ResponseBody
    @Operation(summary = "获取实例变更记录")
    public ResponseBase<IPage<InstanceChangeHisVO>> getInstanceChangeHistory(@RequestBody ChangeHistorySearchParam param) throws Exception {
        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        IPage<InstanceChangeHisVO> pageInfo = operatorLogApi.getOperatorLogByInstanceId(param);
        if (pageInfo == null) {
            return setResultSuccess(new Page<>());
        }
        List<InstanceChangeHisVO> retList = instanceService.getOperatorLogModelInfo(pageInfo.getRecords(), null);
        pageInfo.setRecords(retList);
        return setResultSuccess(pageInfo);
    }

    @PostMapping("/customUpdate")
    @ResponseBody
    @Operation(summary = "流程状态修改")
    public ResponseBase customUpdate(@RequestBody Map map) throws Exception {
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        boolean b = service.customUpdate(map);
        return setResultSuccess();
    }


    @PostMapping("/customBatchUpdate")
    @ResponseBody
    @Operation(summary = "自定义批量修改")
    public ResponseBase customBatchUpdate(@RequestBody List<Map> mapList) throws Exception {
        InstanceServiceImpl service = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        boolean b = service.batchUpdateByInstanceMap(mapList);
        return setResultSuccess();
    }

    @PostMapping("/getOperatorType")
    @ResponseBody
    @Operation(summary = "获取操作类型")
    public ResponseBase<JSONArray> getOperatorType() {
        return setResultSuccess(OperatorTypeDescEnum.getOperatorType());
    }

    @PostMapping("/getOperatorHisPage")
    @ResponseBody
    @Operation(summary = "获取变更历史列表")
    public ResponseBase<IPage<InstanceChangeHisVO>> getOperatorHisPage(@RequestBody AssetsOperatorHisSearchParam param) throws Exception {
        if (StringUtils.hasText(param.getModelId())) {
            CustomModelServiceImpl customModelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
            ModelSearchParam modelSearchParam = new ModelSearchParam();
            modelSearchParam.setGroupId(param.getModelId());
            modelSearchParam.setPage(null);
            List<ModelInfo> modelInfos = customModelService.doSelectShowNormalModelByPath(modelSearchParam);
            if (!CollectionUtils.isEmpty(modelInfos)) {
                List<String> ids = modelInfos.stream().map(ModelInfo::getId).toList();
                param.setModelIds(ids);
            } else {
                param.setModelIds(Collections.singletonList(param.getModelId()));
            }
        }

        InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        List<String> fieldList = param.getFieldList();
        if (CollUtil.isNotEmpty(fieldList)) {
            List<InstanceChangeHisVO> operatorList = operatorLogApi.getOperatorList(param);
            if (CollUtil.isEmpty(operatorList)) {
                return setResultSuccess(new Page<>());
            }
            List<InstanceChangeHisVO> retList = instanceService.getOperatorLogModelInfo(operatorList, param);
            return setResultSuccess(CustomPageUtil.builderIPage(param.getPageNum(), param.getPageSize(), 0, retList));
        }
        IPage<InstanceChangeHisVO> operatorHisPage = operatorLogApi.getOperatorHisPage(param);
        if (operatorHisPage == null) {
            return setResultSuccess(new Page<>());
        }
        List<InstanceChangeHisVO> retList = instanceService.getOperatorLogModelInfo(operatorHisPage.getRecords(), param);
        operatorHisPage.setRecords(retList);
        return setResultSuccess(operatorHisPage);
    }

    @PostMapping("/listScope")
    @ResponseBody
    @Operation(summary = "范围选择组件列表")
    public ResponseBase listScopeData(@RequestBody ListScopeParam param) throws Exception {
        CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
        DataScopeView dataScopeView = modelService.listScopeData(param);
        return setResultSuccess(dataScopeView);
    }

    @PostMapping("/updateDeviceCode")
    @ResponseBody
    @Operation(summary = "更新指纹信息")
    public ResponseBase updateDeviceCode(@RequestBody DeviceCodeParam deviceCodeParam) throws Exception {
        InstanceServiceImpl modelService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
        modelService.updateDeviceCode(deviceCodeParam);
        return setResultSuccess(deviceCodeParam);
    }
}
